<?php
/**
 * Created by PhpStorm.
 * User: paulLu
 * Date: 2016/2/22
 * Time: 13:57
 */
namespace App\Http\Controllers\Job;
use App\Http\Controllers\ApiController;
use App\Http\Components\UserComponent;
use App\library\juhe\Identify;
use App\library\UtilFunction;
use App\Models\ConfigModel;
use App\Models\UserProfileModel;
use App\Models\UserAccountModel;
use App\Models\UserVideoChatModel;
use App\Models\VideoChatModel;
use App\Models\AccountRecordsModel;
use Illuminate\Http\Request;

use App\Http\Components\OuterDataComponent;
use App\library\UtilRegular;

/**
 * 视频聊天
 */
class VideoChatController extends ApiController
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 版本控制，对应app版本跳转对应接口
     * @param Request $request
     * @author paulLu
     */
    /*版本控制，对应app版本跳转对应接口*/
    public function version_invoke($function, Request $request)
    {
        $appversion = $request->input('appversion');
        $apptype = $request->input('apptype');
        if ($appversion && $apptype) {
            try {
                return call_user_func_array(array($this, $function), array($request));
            } catch (\Exception $e) {
                return $this->json('0', '系统错误' . $e->getMessage());
            }
        } else {
            return $this->json('102', '该app版本下无此接口，请更新app');
        }
    }

    /**
     * 提交视频聊天
     */
    public function open(Request $request)
    {
        $user = UserComponent::check_token($request);
        $user_id = $user['user_id'];
        $pictures = $request->input('pictures');
        $videos = $request->input('videos');
        $picture_list = explode(',',$pictures);
        $video_list = explode(',',$videos);
        if(count($picture_list) != 3){
            return $this->json('0','必须上传3张图片');
        }

        if(count($video_list) != 2){
            return $this->json('0','必须上传2段视频');
        }

        foreach($picture_list AS &$pitem){
            $pitem = UtilFunction::getRootImg($pitem);
        }
        foreach($video_list AS &$vitem){
            $vitem = UtilFunction::getRootImg($vitem);
        }
        $userProfile = UserProfileModel::where("user_id",$user_id)->first()->toArray();
        if($userProfile['open_video_chat'] == 1){
            return $this->json('0','您已经通过视频认证，无需申请');
        }

        $userVideoChat = UserVideoChatModel::where("user_id",$user_id)->first();
        if($userVideoChat && $userVideoChat->status == 0){
            return $this->json('0','您的视频认证正在审核，请耐心等待');
        }
        if(!$userVideoChat){
            $video_chat = new UserVideoChatModel();
            $video_chat->user_id = $user_id;
            $video_chat->picture = implode(',',$picture_list);
            $video_chat->video = implode(',',$video_list);
            $result = $video_chat->saveOrFail();
        }else{
            $userVideoChat->picture = implode(',',$picture_list);
            $userVideoChat->video = implode(',',$video_list);
            $userVideoChat->status = 0;
            $result = $userVideoChat->saveOrFail();
        }

        if($result){
            return $this->json('1','上传成功，请等待审核');
        }else{
            return $this->json('0','上传失败');
        }
    }

    /**
     * 查看用户是否可以开通视频聊天，可以视频时间的市场
     */
    public function check(Request $request)
    {
        $user = UserComponent::check_token($request);
        $user_id = $user['user_id'];
        $result = array();
        $receive_user_id = $request->input('receive_user_id');
        if(empty($receive_user_id)){
            return $this->json('0','视频聊天用户ID不能为空');
        }
        //获取视频聊天价格
        $config = new ConfigModel();
        $video_chat_price = $config->get_value('video_chat_price');
        //验证申请开视频用户的余额
        $userAccount = UserAccountModel::where("user_id",$user_id)->first()->toArray();
        $balance = $userAccount["balance"]-$userAccount["frozen"];
        $minu = floor($balance/$video_chat_price);
        $result['chat_time'] = $minu;   //可以聊天XX分钟
        //查看对方用户是否已开通视频聊天
        $userProfile = UserProfileModel::where("user_id",$receive_user_id)->first()->toArray();
        $result["open_video_chat"] = $userProfile["open_video_chat"];
        if($result["chat_time"] >0 && $result["open_video_chat"] == 1){ //可以视频通话 插入视频通话记录
            $videoChat = new VideoChatModel();
            $videoChat->open_user_id = $user_id;
            $videoChat->receive_user_id = $receive_user_id;
            $videoChat->start_time = time();
            $videoChat->video_time = 0;
            $videoChat->price = 0;
            $videoChat->saveOrFail();
            $video_chat_id = $videoChat->getQueueableId();
            $result["video_chat_id"] = $video_chat_id;
        }else{
            $result["video_chat_id"] = 0;
        }
        return $this->json('1','获取成功',$result);;
    }

    /**
     * 视频聊天结束
     */
    public function end(Request $request)
    {
        $user = UserComponent::check_token($request);
        $user_id = $user['user_id'];
        $video_chat_id = $request->input('video_chat_id');    //视频聊天ID
        $video_time = $request->input('video_time');    //聊天总时长 单位秒
        if(empty($video_chat_id)){
            return $this->json('0','视频聊天ID不能为空');
        }
        if(empty($video_time)){
            return $this->json('0','聊天时间不能为空');
        }
        $videoChat = VideoChatModel::where("id",$video_chat_id)->where("open_user_id",$user_id)->first();
        if(!$videoChat){
            return $this->json('0','该视频聊天记录不存在，请重新发起');
        }
        $video_time_minu = ceil($video_time/60);
        //获取视频聊天价格
        $config = new ConfigModel();
        $video_chat_price = $config->get_value('video_chat_price');
        $video_price = $video_chat_price*$video_time_minu;

        //可以聊天的时间（分钟）
        $userAccount = UserAccountModel::where("user_id",$user_id)->first()->toArray();
        $balance = $userAccount["balance"]-$userAccount["frozen"];
        if(($balance-$video_price)<0){
            return $this->json('0','无法结算，用户余额不足，请关闭视频聊天');
        }
        $minu = floor(($balance-$video_price)/$video_chat_price);


        //插入视频通话时间
        $videoChat->video_time = $videoChat->video_time+$video_time;
        $videoChat->price = $videoChat->price+$video_price;

        $result = $videoChat->saveOrFail();
        if($result){
            //结算金额
            UserComponent::price_save("video_chat",$user_id,$video_price,-1,'gold',$video_chat_id);
            UserComponent::price_save("video_chat",$videoChat->receive_user_id,$video_price,1,'gold',$video_chat_id);
            $result = array("video_chat_id"=>$video_chat_id,"chat_time"=>$minu);
            return $this->json('1','操作成功',$result);
        }else{
            return $this->json('0','操作失败');
        }
    }

    /**
     * 查看视频聊天
     */
    public function show(Request $request)
    {
        $user = UserComponent::check_token($request);
        $user_id = $user['user_id'];
        $result = array();
        $userVideoChat = UserVideoChatModel::where("user_id",$user_id)->first();
        if(!$userVideoChat){
            $status = -1;
        }else{
            $status = $userVideoChat->status;
        }
        $result["status"] = $status;

        $model = $request->input('model');    //1 我发起的视频 2我接收的视频
        if(!in_array($model,array(1,2))){
            return $this->json('0','参数有误');
        }
        if($model == 1){
            $list = VideoChatModel::select(['at_user_profile.avatar','at_user_profile.nick_name','at_user_profile.age','at_user_profile.height','at_user_profile.weight','at_video_chat.start_time','at_video_chat.video_time'])->where("at_video_chat.open_user_id",$user_id)
                ->leftJoin("at_user_profile","at_user_profile.user_id","=","at_video_chat.receive_user_id")->get()->toArray();
        }else{
            $list = VideoChatModel::select(['at_user_profile.avatar','at_user_profile.nick_name','at_user_profile.age','at_user_profile.height','at_user_profile.weight','at_video_chat.start_time','at_video_chat.video_time'])->where("at_video_chat.receive_user_id",$user_id)
                ->leftJoin("at_user_profile","at_user_profile.user_id","=","at_video_chat.open_user_id")->get()->toArray();
        }
        foreach($list AS &$item){
            $item["avatar"] = UtilFunction::getUrlImg($item["avatar"]);
            $item["start_time"] = date("Y-m-d H:i",$item["start_time"]);
            $item["video_time"] = UtilFunction::getDesTime($item["video_time"]);
        }
        $result["list"] = $list;
        return $this->json('1','获取成功',$result);
    }

}